package cn.fl.remindconfig.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.constant.McrBillMConstant;
import cn.fl.project.service.IPrjQuatPrpsCfgMService;
import cn.fl.remindconfig.service.ISplRemindConfigService;
import cn.fl.remindconfig.vo.SplRemindConfigVO;
import com.alibaba.fastjson.JSON;
import fl.spl.facade.remindconf.condition.SplRemindConfigQC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;

/**
 * @Description:  控制层
 */
@Controller
@RequestMapping("/remindconfig/splremindconfig")
public class SplRemindConfigController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SplRemindConfigController.class);

	/**
	 * SplRemindConfig 服务层BEAN
	 */
	@Autowired
	private ISplRemindConfigService splRemindConfigService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private IPrjQuatPrpsCfgMService prjQuatPrpsCfgMService;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载到提醒配置列表页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView();
		mav.setViewName("product/splInfo/splRemindConfInfoList");
		//项目类型PRJ0002
		List<KeyValueVO> prjTypCdList = this.getKeyValueList("11000", "0000", "PRJ0002");
		//业务类型
		List<KeyValueVO> busTypCdList = this.getKeyValueList("11000", "0000", "PRJ0023");
		//事业部
		List<KeyValueVO> buOrgCdList = this.prjQuatPrpsCfgMService.searchBuOrgCdList();
		//主体
		List<KeyValueVO> curOrgCdList = this.getKeyValueList("13000", "0000", "SPL0062");
		BaseLogUtils.info(logger, "toListPage", "prjTypCdList.",JSON.toJSONString(prjTypCdList));
		BaseLogUtils.info(logger, "toListPage", "busTypCdList.",JSON.toJSONString(busTypCdList));
		BaseLogUtils.info(logger, "toListPage", "curOrgCdList.",JSON.toJSONString(curOrgCdList));
		BaseLogUtils.info(logger, "toListPage", "buOrgCdList.",JSON.toJSONString(buOrgCdList));
		mav.addObject("prjTypCdList", JSON.toJSONString(prjTypCdList));
		mav.addObject("busTypCdList", JSON.toJSONString(busTypCdList));
		mav.addObject("buOrgCdList", JSON.toJSONString(buOrgCdList));
		mav.addObject("curOrgCdList", JSON.toJSONString(curOrgCdList));
		//---------------------------------
		mav.addObject("_prjTypCdList", prjTypCdList);
		mav.addObject("_busTypCdList", busTypCdList);
		mav.addObject("_buOrgCdList", buOrgCdList);
		mav.addObject("_curOrgCdList", curOrgCdList);
		return mav;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		ModelAndView view = new ModelAndView("remindconfig/splRemindConfig/splRemindConfigAdd");
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载新增.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("remindconfig/splRemindConfig/splRemindConfigModify");
		view.addObject("id", id);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载修改.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("remindconfig/splRemindConfig/splRemindConfigDetail");
		view.addObject("id", id);
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SplRemindConfigQC qc = new SplRemindConfigQC();
		//设置查询条件？
		String buOrgCd = request.getParameter("buOrgCd"); //事业部
		if (StringUtils.isNotBlank(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		String prjTypCd = request.getParameter("prjTypCd"); //项目类型
		if (StringUtils.isNotBlank(prjTypCd)) {
			qc.setPrjTypCd(prjTypCd);
		}
		String curOrgCd = request.getParameter("curOrgCd"); //主体
		if (StringUtils.isNotBlank(curOrgCd)) {
			qc.setCurOrgCd(curOrgCd);
		}
		BaseLogUtils.info(logger, "initList", "-----事业部buOrgCd：" + buOrgCd);
		BaseLogUtils.info(logger, "initList", "-----项目类型prjTypCd：" + prjTypCd);
		BaseLogUtils.info(logger, "initList", "-----主体buOrgCd：" + curOrgCd);
		page.setCondition(qc);

		Pager pager = this.splRemindConfigService.searchListPage(page,"","");
		List<SplRemindConfigVO> list = (List<SplRemindConfigVO>) pager.getResultList();
		ListPageVO<SplRemindConfigVO> listPage = new ListPageVO<SplRemindConfigVO>(list, pager.getTotalCount());
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "add", "新增对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		String buOrgCd = request.getParameter("win_add_buOrgCd");
		String curOrgCd = request.getParameter("win_add_curOrgCd");
		String busTypCd = request.getParameter("win_add_busTypCd");
		String prjTypCd = request.getParameter("win_add_prjTypCd");
		String remindAmtOne = request.getParameter("win_add_remindAmtOne");
		String remindAmtTwo = request.getParameter("win_add_remindAmtTwo");
		String remindAmtThree = request.getParameter("win_add_remindAmtThree");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		SplRemindConfigVO entity = null;
		try {
			entity = new SplRemindConfigVO();
			entity.setBuOrgCd(buOrgCd);
			entity.setCurOrgCd(curOrgCd);
			entity.setBusTypCd(busTypCd);
			entity.setPrjTypCd(prjTypCd);
			if(StringUtils.isBlank(remindAmtOne)){
				entity.setRemindAmtOne(null);
			}else {
				entity.setRemindAmtOne(Double.valueOf(remindAmtOne));
			}
			if(StringUtils.isBlank(remindAmtTwo)){
				entity.setRemindAmtTwo(null);
			}else {
				entity.setRemindAmtTwo(Double.valueOf(remindAmtTwo));
			}
			if(StringUtils.isBlank(remindAmtThree)){
				entity.setRemindAmtThree(null);
			}else {
				entity.setRemindAmtThree(Double.valueOf(remindAmtThree));
			}
			entity.setStatus(0);//启用状态
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
			Long id = this.splRemindConfigService.add(entity,CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd(),"");
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增对象失败,buOrgCd["+buOrgCd+"].curOrgCd["+curOrgCd+"].busTypCd["+busTypCd+"].prjTypCd["+prjTypCd+"].remindAmtOne["+remindAmtOne+"].remindAmtTwo["+remindAmtTwo+"].remindAmtThree["+remindAmtThree+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.info(logger, "add", "新增对象失败,buOrgCd["+buOrgCd+"].curOrgCd["+curOrgCd+"].busTypCd["+busTypCd+"].prjTypCd["+prjTypCd+"].remindAmtOne["+remindAmtOne+"].remindAmtTwo["+remindAmtTwo+"].remindAmtThree["+remindAmtThree+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "add", "新增对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "modify", "修改对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SplRemindConfigVO entity = null;
		try {
			entity = new SplRemindConfigVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.splRemindConfigService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改对象失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "modify", "修改对象失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "modify", "修改对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "remove", "移除对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		try {
			this.splRemindConfigService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "remove", "移除对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "remove", "移除对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "remove", "移除对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "getById", "根据主键获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SplRemindConfigVO vo = this.splRemindConfigService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}
		
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "getById", "根据主键获取对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}
	/**
	 * 作废
	 */
	@RequestMapping(value = "/invalid.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object invalid(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "作废", "作废对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			BaseLogUtils.info(logger, "作废", "作废数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SplRemindConfigVO entity = null;
		try {
			entity = new SplRemindConfigVO();
			entity.setId(Long.valueOf(id));
			entity.setStatus(1);
			//TODO ADD PARAM
			Long success = this.splRemindConfigService.invalid(entity,CurrentThreadContext.getCurrentSysCd(),
					CurrentThreadContext.getCurrentOrgCd(),  "");
			if(success ==0){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
				BaseLogUtils.info(logger, "invalid", "作废失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "invalid", "作废成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "invalid", "作废对象失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.error(logger, "invalid", "作废对象失败,id["+id+"].", CurrentThreadContext.getCurrentUserName(),ex);
		}

		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "modify", "作废对象.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return result;
	}


	public List<KeyValueVO> getKeyValueList(String sysCd,String orgCd,String code) throws BaseException {
		List<KeyValueVO> keyValueList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApiService.searchGroup(sysCd,orgCd, code);
//		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApiService
//				.searchGroup(CurrentThreadContext.getCurrentSysCd(),
//						CurrentThreadContext.getCurrentOrgCd(), code);
		if (CollectionUtils.isNotEmpty(dictionaryList)) {
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCode());
				keyValue.setValue(sysDictionaryDTO.getCodeNm());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}
}

